package com.picket.controller.teams;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.picket.ResourceNotFoundException;
import com.picket.domain.Event;
import com.picket.domain.FileUpload;
import com.picket.domain.Team;
import com.picket.service.IEventService;
import com.picket.service.ITeamService;

@Controller
//@RequestMapping(value = "/teams")
public class TeamsUploadController {
	
	  @ModelAttribute("teamsUploadForm")
	  public TeamsUploadForm createForm() {
	    return new TeamsUploadForm();
	  }
	  
	  
	private IEventService eventService;

	@Required
	public void setEventService(IEventService eventService) {
		this.eventService = eventService;
	}

	  
	private ITeamService teamService;

	@Required
	public void setTeamService(ITeamService teamService) {
		this.teamService = teamService;
	}
	
	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}

	@RequestMapping(value="/admin/teams/upload",method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute(new FileUpload());
		model.addAttribute("events", eventService.getAllEvents());
		return "/teams/uploadTeams";
	}

	@RequestMapping(value="saveTeam",method = RequestMethod.GET)
	public String getTeamSaveForm(Model model) {
		model.addAttribute("events", eventService.getAllEvents());
		return "/teams/saveteam";
	}
	
	@RequestMapping(value="/admin/teams/create",method = RequestMethod.POST)
	public String create(TeamsUploadForm form, BindingResult result,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - "
						+ error.getDefaultMessage());
			}
			return "/teams/uploadTeams";
		}

		// Some type of file processing...
		System.err.println("-------------------------------------------");
		try {
			MultipartFile file = form.getFileUpload().getFileData();
			String fileName = null;
			InputStream inputStream = null;
			// OutputStream outputStream = null;
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				if (file.getSize() > 10000) {
					System.out.println("File Size:::" + file.getSize());
					fileName = file.getOriginalFilename();
					// outputStream = new FileOutputStream(fileName);
					System.out
							.println("fileName:" + file.getOriginalFilename());
					// InputStream inp = new FileInputStream(fileName);
					POIFSFileSystem fs = new POIFSFileSystem(inputStream);
					HSSFWorkbook wb = new HSSFWorkbook(fs);// .create(inputStream);
					Sheet sheet = wb.getSheetAt(0);
					List<Team> teams = new ArrayList<Team>();
					for(int rowId=0; rowId<sheet.getLastRowNum();rowId++){
						if(rowId==0){
							continue;
						}
						Row row = sheet.getRow(rowId);
						Cell teamName = row.getCell(0);
						Cell teamCode = row.getCell(1);
						//Event ec = eventService.getEvent(form.getSelected());
						Team team = new Team(teamName.getStringCellValue(),teamCode.getStringCellValue(), form.getSelected());
						teams.add(team);
					}
					teamService.create(teams);

					return "redirect:/admin/teams/all";
				}
				inputStream.close();
			}

			// ..........................................
			session.setAttribute("uploadFile", file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/forms/uploadfileindex";
	}

	
	@RequestMapping(value="/admin/teams/all", method=RequestMethod.GET)
	public String getView( Model model) {
		Collection<Team> teams = teamService.getAllTeams();

		model.addAttribute("teams", teams);
		return "/teams/viewall";
	}
}